package com.wmh.baseservice.common.redis.listener;

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import java.util.regex.Matcher;

/**
 * @author 谢骏
 * @date 2023/11/8 14:04
 **/
public abstract class AbstractExpirationListenerHandler extends KeyExpirationEventMessageListener {

    /**
     * Creates new {@link MessageListener} for {@code __keyevent@*__:expired} messages.
     *
     * @param listenerContainer must not be {@literal null}.
     */
    protected AbstractExpirationListenerHandler(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = message.toString();
        if (this.matcher(key) != null && this.matcher(key).find()) {
            this.onMessage(key);
        }
    }

    /**
     * 过期监听回调方法
     *
     * @param key 过期 key 值
     */
    public abstract void onMessage(String key);

    /**
     * 实现该方法来通过正则 监听回调生效的 key 值
     *
     * @param key 过期key
     * @return 正则对象 null 时 监听器无效
     */
    public abstract Matcher matcher(String key);
}
